﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RMS.Common;
using RMS.DB;

//using Microsoft.Reporting.WinForms;

namespace RMS
{
    public partial class frmStatistic : Form
    {
        private readonly InventoryMng inventoryMng = new InventoryMng();
        //private readonly LooseStoneMng _stoneMng = new LooseStoneMng();
        private readonly ConfigurationMng _configurationMng = new ConfigurationMng();
        private readonly SupplierMng _supplierMng = new SupplierMng();
        private readonly SoldItemsMng soldItemsMng = new SoldItemsMng();
        public frmStatistic()
        {
            InitializeComponent();
            panelLogin.Visible = false;
            tabMain.Visible = true;
        }

        private void frmStatistic_Load(object sender, EventArgs e)
        {
            dateTimePicker1.Value = dateTimePicker2.Value = DateTime.Now;
            dataGridView1.AutoGenerateColumns = dataGridView2.AutoGenerateColumns = dataGridSoldItems.AutoGenerateColumns = false;
            // TAB BIEU DO
            //for (int i = 2010; i < 2021; i++)
            //{
            //    cmbFromYear.Items.Add(i);
            //    cmbToYear.Items.Add(i);
            //    cmbYearF.Items.Add(i);
            //    cmbYearT.Items.Add(i);
            //}
            //for (int j = 1; j <= 12; j++)
            //{
            //    cmbMonthF.Items.Add(j);
            //    cmbMonthT.Items.Add(j);
            //}
            //cmbToYear.SelectedItem = cmbFromYear.SelectedItem = cmbYearF.SelectedItem = cmbYearT.SelectedItem = DateTime.Today.Year;
            //cmbMonthF.SelectedItem = cmbMonthT.SelectedItem = DateTime.Today.Month;
            //pnlByYear.Visible = false;

            BindDataCmbBoxG();

            btnListAllGold_Click(null, null);
            BindDataToInvoiceList();
        }

        private void BindDataCmbBoxG()
        {
            var listCategory = _configurationMng.GetAllItems(Constants.CategoryType);
            var listSupply = _supplierMng.GetAllItems();
            foreach (var item in listCategory)
            {
                if (!string.IsNullOrEmpty(item.Name))
                {
                    cmbCategory.Items.Add(item.Name);
                }
            }
            foreach (var item in listSupply)
            {
                cmbSupply.Items.Add(item.ID);
            }
        }


        private void btnOK_Click(object sender, EventArgs e)
        {
            if (Utilities.VerifyAdmin(textBox1.Text))
            {
                panelLogin.Visible = false;
                tabMain.Visible = true;
            }
            else
            {
                MessageBox.Show(Constants.WrongPasswordMess);
                textBox1.Clear();
                textBox1.Focus();
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            DateTime fDate = new DateTime(dateTimePicker1.Value.Year, dateTimePicker1.Value.Month, dateTimePicker1.Value.Day, 0, 0, 0);
            DateTime tDate = new DateTime(dateTimePicker2.Value.Year, dateTimePicker2.Value.Month, dateTimePicker2.Value.Day, 23, 59, 59);
            if (DateTime.Compare(tDate, fDate) >= 0)
            {
                string title = String.Format("Thống kê từ {0}/{1}/{2} đến {3}/{4}/{5}", fDate.Day, fDate.Month, fDate.Year, tDate.Day, tDate.Month, tDate.Year);
                lbTitle.Text = title;
                double[] invoice = new double[4];
                InvoicesMng invoiceManage = new InvoicesMng();
                invoice  = invoiceManage.GetInvoiceByDate(fDate, tDate);

                double incomeGold = invoice[0];
                double costGold = invoice[1];

                //lbDTDa.Text = Utilities.FormatNumber(Convert.ToDecimal(incomeStone), Utilities.PrecisionFormat);
                lbDTVang.Text = Utilities.FormatNumber(Convert.ToDecimal(incomeGold), Utilities.PrecisionFormat);
                //lbDTTong.Text = Utilities.FormatNumber(Convert.ToDecimal((incomeGold + incomeStone)), Utilities.PrecisionFormat);
                //lbLNDa.Text = Utilities.FormatNumber(Convert.ToDecimal((incomeStone - costStone)), Utilities.PrecisionFormat);
                lbLNVang.Text = Utilities.FormatNumber(Convert.ToDecimal((incomeGold - costGold)), Utilities.PrecisionFormat);
                //lbLNTong.Text = Utilities.FormatNumber(Convert.ToDecimal((incomeGold + incomeStone - costGold - costStone)), Utilities.PrecisionFormat);
                if (tableReport.Visible == false)
                    tableReport.Visible = true;
            }
            else
                MessageBox.Show(Constants.InvalidDatesMess);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            DateTime today = DateTime.Today;
            dateTimePicker1.Value = new DateTime(today.Year, today.Month, today.Day, 0, 0, 0);
            dateTimePicker2.Value = new DateTime(today.Year, today.Month, today.Day, 23, 59, 59);
            button2_Click(null, null);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            DateTime today = DateTime.Today;
            dateTimePicker1.Value = new DateTime(today.Year, today.Month, 1, 0, 0, 0);
            dateTimePicker2.Value = new DateTime(today.Year, today.Month, DateTime.DaysInMonth(today.Year, today.Month), 23, 59, 59);
            button2_Click(null, null);
        }

        private void button5_Click(object sender, EventArgs e)
        {
            DateTime today = DateTime.Today;
            int lastM_M;
            int lastM_Y;

            if (today.Month == 1)
            {
                lastM_M = 12;
                lastM_Y = today.Year - 1 ;
            }
            else
            {
                lastM_M = today.Month - 1;
                lastM_Y    = today.Year;
            }

            dateTimePicker1.Value = new DateTime(lastM_Y, lastM_M, 1, 0, 0, 0);
            dateTimePicker2.Value = new DateTime(lastM_Y, lastM_M, DateTime.DaysInMonth(lastM_Y, lastM_M), 23, 59, 59);
            button2_Click(null, null);
        }

        private void button7_Click(object sender, EventArgs e)
        {
            DateTime today = DateTime.Today;
            dateTimePicker1.Value = new DateTime(today.Year, 1, 1, 0, 0, 0);
            dateTimePicker2.Value = new DateTime(today.Year, 12, 31, 23, 59, 59);
            button2_Click(null, null);
        }

        private void button6_Click(object sender, EventArgs e)
        {
            int fMonth, lMonth;
            DateTime today = DateTime.Today;
            if (1 <= today.Month && today.Month <= 3)
            {
                fMonth = 1;
                lMonth = 3;
            }
            else
                if (today.Month <= 6)
                {
                    fMonth = 4;
                    lMonth = 6;
                }
                else
                    if (today.Month <= 9)
                    {
                        fMonth = 7;
                        lMonth = 9;
                    }
                    else
                    {
                        fMonth = 10;
                        lMonth = 12;
                    }
            dateTimePicker1.Value = new DateTime(today.Year, fMonth, 1, 0, 0, 0);
            dateTimePicker2.Value = new DateTime(today.Year, lMonth, DateTime.DaysInMonth(today.Year, lMonth), 23, 59, 59);
            button2_Click(null, null);
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                btnOK_Click(null, null);
        }

        private void tabMain_Selecting(object sender, TabControlCancelEventArgs e)
        {
            if (tabMain.SelectedTab == tabDoanhthu)
            {
                tabMain.Width = 760;
                tabMain.Height = 580;
            }
            else
                if (tabMain.SelectedTab == tabKho)
                {
                    tabMain.Width = 974;
                    tabMain.Height = 580;
                }
                else
                {
                    tabMain.Width = 974;
                    tabMain.Height = 580;
                }
        }

        private void setLabelGold(List<Inventory> dataSrc)
        {
            int? quantity = 0;
            decimal? cost = 0;
            foreach (var item in dataSrc)
            {
                quantity += item.Quantity;
                cost += item.ImportPrice * item.Quantity;
            }
            lbCostGold.Text = String.Format("{0}{1}", Constants.TotalCost, Utilities.FormatNumber(Convert.ToDecimal(cost), Utilities.PrecisionFormat));
            lbQuantityGold.Text = String.Format("{0}{1} SP", Constants.TotalQuantity, Utilities.FormatNumber(Convert.ToDecimal(quantity), Utilities.PrecisionFormat));
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            var dataSrc = inventoryMng.GetAvailInventoryByElements(txtCode.Text.Trim(), cmbCategory.Text.Trim(), cmbSupply.Text.Trim());
            dataGridView1.DataSource = dataSrc;
            setLabelGold(dataSrc);
        }

        private void btnListAllGold_Click(object sender, EventArgs e)
        {
            var dataSrc = inventoryMng.GetAvailInventoryByElements("", "", "");
            dataGridView1.DataSource = dataSrc;
            setLabelGold(dataSrc);
        }


        ////////////////// CHART ////////////////////////


        #region Event Handlers
        // TAB BIEU DO

        //private void CheckedChange(object sender, EventArgs e)
        //{
        //    pnlByMonth.Visible = !rdioBtnByYear.Checked;
        //    pnlByYear.Visible = rdioBtnByYear.Checked;
        //}

        //private void btnView_Click(object sender, EventArgs e)
        //{
        //    var data = new List<ReportModel>();
        //    if (rdioBtnByMonth.Checked)
        //    {
        //        data = ReportUtils.GetDataForMonthlyReport(Convert.ToInt32(cmbMonthF.SelectedItem), Convert.ToInt32(cmbYearF.SelectedItem), Convert.ToInt32(cmbMonthT.SelectedItem), Convert.ToInt32(cmbYearT.SelectedItem));

        //    }
        //    else
        //    {
        //        if (cmbFromYear.SelectedIndex != -1 && cmbToYear.SelectedIndex != -1 &&
        //            Convert.ToInt32(cmbFromYear.SelectedItem) <= Convert.ToInt32(cmbToYear.SelectedItem))
        //        {
        //            data = ReportUtils.GetDataForYearlyReport(Convert.ToInt32(cmbFromYear.SelectedItem),
        //                                                      Convert.ToInt32(cmbToYear.SelectedItem));
        //            //SmartShopDesktop.Report.BudgetReport.rdlc
        //            reportViewer.LocalReport.ReportEmbeddedResource = "RMS.RevenueReportByYear.rdlc";
        //        }
        //    }
        //    //PrintInvoice form = new PrintInvoice(data);
        //    //form.ShowDialog(this);
        //    ReportModelBindingSource.DataSource = data;
        //    this.reportViewer.RefreshReport();
        //}

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (msg.WParam.ToInt32() == (int)Keys.Escape)
            {
                Close();
            }
            else
            {
                return base.ProcessCmdKey(ref msg, keyData);
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        #endregion


        // danh sach don hang da ban
        private readonly InvoicesMng _invoices = new InvoicesMng();
        private void BindDataToInvoiceList()
        {
            dataGridView3.AutoGenerateColumns = false;
            var src = _invoices.GetCompleteInvoices();
            dataGridView3.DataSource = src;
            dataGridView3.ClearSelection();
            btnDel.Enabled = false;
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(Constants.Msg.DelInvoice, "Chú ý", MessageBoxButtons.YesNo) != DialogResult.Yes)
                return;
            foreach (DataGridViewRow row in dataGridView3.Rows)
            {
                if (row.Selected)
                {
                    _invoices.DeleteItem(Convert.ToString(row.Cells[5].Value));
                }
            }
            dataGridSoldItems.DataSource = null;
            BindDataToInvoiceList();
        }

        private void btnTimkiem_Click(object sender, EventArgs e)
        {
            dataGridView3.DataSource = _invoices.GetInvoiceById(txtSearch.Text.Trim());
        }

        private void button9_Click(object sender, EventArgs e)
        {
            BindDataToInvoiceList();
        }

        private void dataGridView3_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            foreach (DataGridViewRow row in dataGridView3.Rows)
            {
                if (row.Selected)
                {
                    btnDel.Enabled = true;
                    var items = soldItemsMng.GetListItems(Convert.ToString(row.Cells[5].Value));
                    if (items.Count > 0)
                        dataGridSoldItems.DataSource = items;
                    else
                        dataGridSoldItems.DataSource = null;
                }
            }
        }

        private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                btnTimkiem_Click(sender, e);
        }
    }
}
